#include "tmscriptrun.h"

TmScriptRun::TmScriptRun()
{
    m_pModule = NULL;
    m_bExit = false;
    m_bLoad = false;
}

bool TmScriptRun::GetIsRunning()
{
    return m_bIsRunning;
}

void TmScriptRun::SetStop()
{
    m_bIsRunning = false;
    m_bLoad = false;
}

void TmScriptRun::SetExit()
{
    m_bExit = true;
}

void TmScriptRun::LoadScript(QString strPath)
{
    QFile f_src(strPath);
    QByteArray b_src;
    if( f_src.open(QIODevice::ReadOnly) ){
        b_src = f_src.readAll();
        f_src.close();
    }
    LoadContent(b_src);
    m_strPath = strPath;
}

void TmScriptRun::LoadContent(QByteArray bContent)
{
    m_strPath = "Null";
    QFile f_dst("./TamiScript.py");
    if( f_dst.open(QIODevice::WriteOnly) ){
        f_dst.write(bContent);
        f_dst.close();
    }
    m_bLoad = true;
}

QString TmScriptRun::GetScriptPath()
{
    return m_strPath;
}

void TmScriptRun::run()
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    PyImport_ImportModule("RobotProxy");

    while( !m_bExit ) {
        msleep(99);
        QCoreApplication::processEvents();
        if( !m_bLoad){
            continue;
        }
        m_bIsRunning = false;
        // load
        if( !m_pModule ){
            m_pModule = PyImport_ImportModule("TamiScript");
        }else{
            PyImport_ReloadModule(m_pModule);
        }
        //        qDebug()<<m_pModule;
        m_bLoad = false;

        if( !m_pModule ){
            continue;
        }
        m_bIsRunning = true;

        qDebug()<<"Start Run Scripts.";
        m_pFuncInit = PyObject_GetAttrString(m_pModule,"On_Init");
        m_pFuncRun = PyObject_GetAttrString(m_pModule,"On_Run");
        m_pFuncStop = PyObject_GetAttrString(m_pModule,"On_Stop");

        //        qDebug()<<m_pFuncInit<<m_pFuncRun<<m_pFuncStop;

        if( m_pFuncInit ){
            PyEval_CallObject(m_pFuncInit, NULL);
        }
        if( m_pFuncRun ){
            while( m_bIsRunning ){
                PyObject* pRet = PyEval_CallObject(m_pFuncRun, NULL);
                if( !PyObject_IsTrue(pRet) || m_bExit || m_bLoad ){
                    m_bIsRunning = false;
                    break;
                }
                msleep(99);
                QCoreApplication::processEvents();
            }
        }
        if( m_pFuncStop ){
            PyEval_CallObject(m_pFuncStop, NULL);
        }

        PyRun_SimpleString("app.CbNotify=None");

        m_bIsRunning = false;
        m_pFuncInit = NULL;
        m_pFuncRun = NULL;
        m_pFuncStop = NULL;
        PyRun_SimpleString("sys.stdout.flush()");
        m_strPath = "";

    }
}
